Multiple Row Subquery


Introduction to Multiple Row Subquery

In the world of SQL (Structured Query Language), subqueries are powerful tools that allow for complex data retrieval and manipulation. One of the variations of subqueries is the "Multiple Row Subquery," a concept worth exploring for its versatility in handling data across multiple rows within a database.

What is a Multiple Row Subquery?

A multiple row subquery, as the name suggests, is a query within a query that returns multiple rows of data. Unlike a single-row subquery that operates on a single result, a multiple row subquery deals with sets of data, enabling comparisons, filtering, and manipulation across multiple records simultaneously.

Syntax and Usage:

The syntax for a multiple row subquery involves using operators like IN, ANY, or ALL to compare a single value with the result set of a subquery.

Let's delve into an example to better illustrate its usage:

Consider a hypothetical scenario where you have two tables: Employees and Salaries. The Employees table contains employee information, while the Salaries table holds salary details for these employees.

Employees Table:

EmployeeID

Name

Department

1

John

Sales

2

Emily

Marketing

3

Michael

HR

4

Sophia

Sales

....

....

....

Salaries Table:

EmployeeID

Salary

1

50000

2

48000

3

55000

4

52000

...

...

Example:

Let's say you want to retrieve the names of employees who earn a salary greater than the average salary of all employees. This is where a multiple row subquery can be employed:

SELECT Name

FROM Employees

WHERE EmployeeID IN (

SELECT EmployeeID

FROM Salaries

WHERE Salary > (

SELECT AVG(Salary)

FROM Salaries

)

);

This SQL query breaks down as follows:

  • The innermost query calculates the average salary from the Salaries table.
  • The middle query retrieves the EmployeeID of employees earning salaries higher than the average salary.
  • The outer query then uses these EmployeeID values to fetch the names of those specific employees from the Employees table.

Benefits and Use Cases:

  • Complex Filtering: Multiple row subqueries allow for intricate filtering based on aggregate functions, making it convenient to compare data across multiple rows.
  • Data Manipulation: It enables performing calculations or operations on sets of data, such as finding employees with salaries meeting certain criteria.
  • Subquery Optimization: While powerful, using multiple row subqueries extensively might impact performance. Optimizing queries through indexing and efficient query structuring is advisable.


Multiple row subqueries are a fundamental aspect of SQL, offering a way to handle data collectively across multiple records. Understanding their syntax and application can significantly enhance the capabilities of SQL developers and analysts, enabling them to perform complex data manipulations and retrievals efficiently.